// 添加环境检测和导出逻辑
class ApiClient {
    constructor() {
        // 适配Node.js测试环境
        const isBrowser = typeof window !== 'undefined';
        this.gatewayUrl = isBrowser ? (window.GATEWAY_URL || 'http://localhost:3000') : 'http://localhost:3000';
        this.wsGatewayUrl = isBrowser ? (window.WS_GATEWAY_URL || 'ws://localhost:3000') : 'ws://localhost:3000';
        this.token = null;
        this.tokenExpiry = null;
        // 为测试环境提供axios实例
        this.axios = isBrowser ? window.axios : require('axios');
    }

    // 登录方法
    async login(username, password) {
        try {
            const response = await axios.post(`${this.gatewayUrl}/api/auth/login`, {
                username,
                password
            });
            this.token = response.data.token;
            this.tokenExpiry = new Date().getTime() + (60 * 60 * 1000); // 假设令牌1小时后过期
            return response.data;
        } catch (error) {
            console.error('Login failed:', error);
            throw new Error(`登录失败: ${error.message || '未知错误'}`);
        }
    }

    // 刷新令牌
    async refreshToken() {
        if (!this.token) {
            throw new Error('没有可用的令牌，请先登录');
        }

        try {
            const response = await axios.post(`${this.gatewayUrl}/api/auth/refresh`, {}, {
                headers: { 'Authorization': `Bearer ${this.token}` }
            });
            this.token = response.data.token;
            this.tokenExpiry = new Date().getTime() + (60 * 60 * 1000);
            return response.data;
        } catch (error) {
            console.error('Token refresh failed:', error);
            throw new Error(`令牌刷新失败: ${error.message || '未知错误'}`);
        }
    }

    // 检查令牌是否有效
    _isTokenValid() {
        if (!this.token || !this.tokenExpiry) {
            return false;
        }
        return new Date().getTime() < this.tokenExpiry;
    }

    // 确保令牌有效
    async _ensureValidToken() {
        if (!this._isTokenValid()) {
            await this.refreshToken();
        }
        return this.token;
    }

    // 获取公开数据
    async getPublicData() {
        try {
            const response = await axios.get(`${this.gatewayUrl}/api/public`);
            return response.data;
        } catch (error) {
            console.error('Failed to get public data:', error);
            throw new Error(`获取公开数据失败: ${error.message || '未知错误'}`);
        }
    }

    // 获取受保护数据
    async getProtectedData() {
        try {
            const token = await this._ensureValidToken();
            const response = await axios.get(`${this.gatewayUrl}/api/protected`, {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            return response.data;
        } catch (error) {
            console.error('Failed to get protected data:', error);
            throw new Error(`获取受保护数据失败: ${error.message || '未知错误'}`);
        }
    }

    // 访问服务1 API
    async getService1Data() {
        try {
            const token = await this._ensureValidToken();
            const response = await axios.get(`${this.gatewayUrl}/api/service1/data`, {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            return response.data;
        } catch (error) {
            console.error('Failed to get service1 data:', error);
            throw new Error(`获取服务1数据失败: ${error.message || '未知错误'}`);
        }
    }

    // 访问服务2 API
    async getService2Data() {
        try {
            const token = await this._ensureValidToken();
            const response = await axios.get(`${this.gatewayUrl}/api/service2/data`, {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            return response.data;
        } catch (error) {
            console.error('Failed to get service2 data:', error);
            throw new Error(`获取服务2数据失败: ${error.message || '未知错误'}`);
        }
    }

    // 连接WebSocket
    async connectWebSocket(_path) {
        try {
            const _token = await this._ensureValidToken();
            // 确保WebSocket路径以/ws/开头
            let _normalizedPath = ""
            if (_path.startsWith('/ws/')) {
                _normalizedPath = _path;
            } else {
                _normalizedPath = `/ws${_path.startsWith('/') ? _path : `/${_path}`}`;
            }

            // 使用查询参数传递token
            const wsUrl = `${this.wsGatewayUrl}${_normalizedPath}?token=${encodeURIComponent(_token)}`;
            const ws = new WebSocket(wsUrl);

            return new Promise((resolve, reject) => {
                const timeout = setTimeout(() => {
                    reject(new Error('WebSocket连接超时'));
                }, 5000);

                ws.onopen = () => {
                    clearTimeout(timeout);
                    console.log('WebSocket connection established');
                    resolve(ws);
                };

                ws.onerror = (error) => {
                    clearTimeout(timeout);
                    console.error('WebSocket error:', error);
                    reject(new Error(`WebSocket连接错误: ${error.message || '未知错误'}`));
                };

            });
        } catch (error) {
            console.error('Failed to connect WebSocket:', error);
            throw error;
        }
    }
}

// 导出类，支持CommonJS和ES模块
if (typeof module !== 'undefined' && module.exports) {
    module.exports = ApiClient;
} else if (typeof window !== 'undefined') {
    window.ApiClient = ApiClient;
}